package model

import (
	"time"
	"gorm.io/gorm"
)

type Order struct {
	Id            int64      `json:"id" gorm:"primaryKey;autoIncrement"`
	OrderNo       string     `json:"orderNo" gorm:"uniqueIndex;size:50;not null"`
	UserId        int64      `json:"userId" gorm:"not null;index"`
	UserName      string     `json:"userName" gorm:"size:100;not null"`
	FuelType      string     `json:"fuelType" gorm:"size:50;not null"`
	FuelPrice     float64    `json:"fuelPrice" gorm:"type:decimal(10,2);not null"`
	Volume        float64    `json:"volume" gorm:"type:decimal(10,2);not null"`
	PrepaidAmount float64    `json:"prepaidAmount" gorm:"type:decimal(10,2);not null"`
	ActualVolume  *float64   `json:"actualVolume" gorm:"type:decimal(10,2)"`
	ActualAmount  *float64   `json:"actualAmount" gorm:"type:decimal(10,2)"`
	Status        string     `json:"status" gorm:"type:enum('pending','fueling','completed','cancelled');default:'pending';index"`
	CreateTime    time.Time  `json:"createTime" gorm:"autoCreateTime;index"`
	UpdateTime    time.Time  `json:"updateTime" gorm:"autoUpdateTime"`
	CompleteTime  *time.Time `json:"completeTime"`
}

func (Order) TableName() string {
	return "orders"
}

type OrderModel struct {
	db *gorm.DB
}

func NewOrderModel(db *gorm.DB) *OrderModel {
	return &OrderModel{db: db}
}

func (m *OrderModel) Create(order *Order) error {
	return m.db.Create(order).Error
}

func (m *OrderModel) FindById(id int64) (*Order, error) {
	var order Order
	err := m.db.First(&order, id).Error
	return &order, err
}

func (m *OrderModel) FindList(status string, userId int64, isAdmin bool, page, size int64) ([]Order, int64, error) {
	var orders []Order
	var total int64
	
	query := m.db.Model(&Order{})
	
	// 添加状态过滤条件
	if status != "" {
		query = query.Where("status = ?", status)
	}
	
	// 如果不是管理员，只查询用户自己的订单
	if !isAdmin && userId > 0 {
		query = query.Where("user_id = ?", userId)
	}
	
	// 获取总数
	err := query.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	
	// 分页查询
	offset := (page - 1) * size
	err = query.Offset(int(offset)).Limit(int(size)).Order("create_time DESC").Find(&orders).Error
	
	return orders, total, err
}

func (m *OrderModel) Complete(id int64, actualVolume, actualAmount float64) (*Order, error) {
	now := time.Now()
	err := m.db.Model(&Order{}).Where("id = ?", id).Updates(map[string]interface{}{
		"actual_volume":  actualVolume,
		"actual_amount":  actualAmount,
		"status":         "completed",
		"complete_time":  &now,
	}).Error
	
	if err != nil {
		return nil, err
	}
	
	return m.FindById(id)
}